package com.yanqu.road.dao.impl.player;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.banquet.UserBanquetData;
import com.yanqu.road.entity.enums.eBanquetInfoType;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.utils.string.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UserBanquetDaoImpl extends TempDataObjectDao<UserBanquetData> {

    public int getUserBanquetNormalCount(long userId) {
        List<Integer> normalTypeList = new ArrayList<>();
        normalTypeList.add(eBanquetInfoType.SimpleBanquet.getValue());
        normalTypeList.add(eBanquetInfoType.RichBanquet.getValue());
        normalTypeList.add(eBanquetInfoType.ChildBanquet.getValue());
        normalTypeList.add(eBanquetInfoType.MarryBanquet.getValue());
        normalTypeList.add(eBanquetInfoType.EstateBanquet.getValue());
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select count(1) as normalBanquetCount from t_u_banquet where userId = ? AND isSendReward = 1 AND " +
                " `type` in (" + StringUtils.listToString(normalTypeList, ",") + ")";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            int i = 1;
            call.setLong(i++, userId);
            rs = call.executeQuery();
            while (rs.next()) {
                return rs.getInt("normalBanquetCount");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return 0;
    }

    public Map<String, UserBanquetData> getRunningUserBanquetMap() {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_u_banquet where isSendReward = 0";
        Map<String, UserBanquetData> res = new ConcurrentHashMap<>();
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);

            rs = call.executeQuery();
            while (rs.next()) {
                UserBanquetData data = parse(rs);
                res.put(data.getBanquetId(),data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return res;
    }

    public Map<String, UserBanquetData> getAllUserBanquetMap() {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_u_banquet";
        Map<String, UserBanquetData> res = new ConcurrentHashMap<>();
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);

            rs = call.executeQuery();
            while (rs.next()) {
                UserBanquetData data = parse(rs);
                res.put(data.getBanquetId(),data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return res;
    }

    @Override
    protected boolean addData(UserBanquetData data) {
        PreparedStatement call = null;
        String sql = "insert into t_u_banquet(banquetId,userId,`type`,invitationId,openTime,isSendReward," +
                "popularity,integral,overTime,userCount,invitationInfo,userBaseInfo)" +
                " values(?,?,?,?,?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setString(i++, data.getBanquetId());
            call.setLong(i++, data.getUserId());
            call.setInt(i++, data.getType());
            call.setString(i++, data.getInvitationId());
            call.setLong(i++, data.getOpenTime());
            call.setBoolean(i++, data.isSendReward());
            call.setLong(i++, data.getPopularity());
            call.setLong(i++, data.getIntegral());
            call.setLong(i++, data.getOverTime());
            call.setInt(i++, data.getUserCount());
            call.setString(i++, data.getInvitationInfo());
            call.setString(i++, data.getUserBaseInfoJsonStr());

            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected boolean updateData(UserBanquetData data) {
        PreparedStatement call = null;
        String sql = "UPDATE t_u_banquet SET isSendReward=?,popularity=?,integral=?,userCount=?,invitationInfo=? where banquetId=?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setBoolean(i++, data.isSendReward());
            call.setLong(i++, data.getPopularity());
            call.setLong(i++, data.getIntegral());
            call.setLong(i++, data.getUserCount());
            call.setString(i++, data.getInvitationInfo());
            call.setString(i++, data.getBanquetId());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected UserBanquetData parseData(ResultSet rs) throws SQLException {
        UserBanquetData data = new UserBanquetData();
        data.setBanquetId(rs.getString("banquetId"));
        data.setUserId(rs.getLong("userId"));
        data.setType(rs.getInt("type"));
        data.setInvitationId(rs.getString("invitationId"));
        data.setOpenTime(rs.getLong("openTime"));
        data.setSendReward(rs.getBoolean("isSendReward"));
        data.setPopularity(rs.getLong("popularity"));
        data.setIntegral(rs.getLong("integral"));
        data.setUserCount(rs.getInt("userCount"));
        data.setOverTime(rs.getLong("overTime"));
        data.setInvitationInfo(rs.getString("invitationInfo"));
        String baseUserInfoStr = rs.getString("userBaseInfo");
        if(null == baseUserInfoStr){
            baseUserInfoStr = "";
        }
        UserBaseInfo userBaseInfo = JSON.parseObject(baseUserInfoStr, new TypeReference<UserBaseInfo>() {});
        if(null != userBaseInfo) {
            data.setUserBaseInfo(userBaseInfo);
        }
        return data;
    }
}
